/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Common.Global;
import DAO.AccountDAO;
import DAO.MessageDAO;
import hibernate.entity.Account;
import hibernate.entity.ReceivedMessage;
import hibernate.entity.SentMessage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Tùng
 */
public class MessageController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String urlreceived = "MessageController?btAction=LoadReceivedMessage";
        String urlsent = "MessageController?btAction=LoadSendMessage";
        try {
            String action = request.getParameter("btAction");
            if (action.equals("CreateNewMessage")) {
                session.setAttribute("CREATEMESSAGE", out);
                response.sendRedirect(Common.Global.createmesspage);
            } else if (action.equals("SendMessage")) {
                session.removeAttribute("READSEMESS");
                session.removeAttribute("READREMESS");
                Account getAcc = (Account) session.getAttribute("ACCOUNT");
                if (getAcc != null) {
                    int sentAccID = getAcc.getAccountID();
                    String sentEmail = getAcc.getEmailAddress();
                    String content = request.getParameter("txtSendContent");
                    String subject = request.getParameter("txtSubject");
                    String errorMail = "";
                    String successMail = "";
                    String receivedEmail = request.getParameter("txtReceivedEmail");
                    String list[] = receivedEmail.split(";");
                    for (int i = 0; i < list.length; i++) {
                        AccountDAO checkAccDAO = new AccountDAO();
                        Account checkAcc = checkAccDAO.checkEmail(list[i].trim());
                        if (checkAcc != null) {
                            int receivedAccID = checkAcc.getAccountID();
                            MessageDAO sentAccDAO = new MessageDAO();
                            sentAccDAO.sendMessage(sentAccID, list[i], subject, content);
                            MessageDAO receivedAccDAO = new MessageDAO();
                            String receivedStatus = "unread";
                            receivedAccDAO.receivedMessage(receivedAccID, sentEmail, subject, content, receivedStatus);
                            successMail += list[i] + " ";
                        } else {
                            errorMail += list[i] + " ";
                        }
                    }
                    if (!successMail.equals("")) {
                        session.setAttribute("SENDMESSAGESUCESS", "Message is sent to " + successMail + "!!!");
                    }
                    if (!errorMail.equals("")) {
                        session.setAttribute("SENDMESSAGEERROR", "Message can't be sent to " + errorMail + "!!!");
                    }
                    response.sendRedirect(urlsent);
                } else {
                    response.sendRedirect(Global.loginpage);
                }
            } else if (action.equals("LoadReceivedMessage")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    MessageDAO mess = new MessageDAO();
                    List<ReceivedMessage> result = mess.getReceivedMessage(acc.getAccountID());
                    session.setAttribute("RECEIVEDMESS", result);
                    response.sendRedirect(Common.Global.messpage);
                } else if (acc == null) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("LoadSendMessage")) {
                Account acc = (Account) session.getAttribute("ACCOUNT");
                if (acc != null) {
                    MessageDAO mess = new MessageDAO();
                    List<SentMessage> result = mess.getSentMessage(acc.getAccountID());
                    session.setAttribute("SENTMESS", result);
                    response.sendRedirect(Common.Global.createmesspage);
                } else if (acc == null) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("readReMess")) {
                int messID = Integer.parseInt(request.getParameter("readMessageID"));
                MessageDAO message = new MessageDAO();
                ReceivedMessage mess = message.checkReMess(messID);
                if (mess != null) {
                    session.setAttribute("READREMESS", mess);
                    String checkStatus = mess.getReStatus();
                    if (checkStatus.equals("unread")) {
                        message.updateReceivedMessage(messID);
                    }
                } else {
                    session.setAttribute("READREERR", "Sorry! Can't read that message");
                }
                response.sendRedirect(urlreceived);
            } else if (action.equals("readSeMess")) {
                int messID = Integer.parseInt(request.getParameter("readSeMessageID"));
                MessageDAO message = new MessageDAO();
                SentMessage mess = message.checkSeMess(messID);
                if (mess != null) {
                    session.setAttribute("READSEMESS", mess);
                } else {
                    session.setAttribute("READSEERR", "Sorry! Can't read that message");
                }
                response.sendRedirect(urlsent);
            } else if (action.equals("Close")) {
                session.removeAttribute("READSEMESS");
                session.removeAttribute("READREMESS");
                session.removeAttribute("REPLYMESS");
                response.sendRedirect(urlreceived);
            } else if (action.equals("CloseSentMessage")) {
                session.removeAttribute("READSEMESS");
                session.removeAttribute("REPLYMESS");
                response.sendRedirect(urlsent);
            } else if (action.equals("replyMess")) {
                String replyEmail = request.getParameter("replyEmail");
                session.setAttribute("REPLYMESS", replyEmail);
                String replySubject = request.getParameter("replySubject");
                session.setAttribute("REPLYMESSSUB", replySubject);
                response.sendRedirect(Common.Global.messpage);
            } else if (action.equals("repMessage")) {
                session.removeAttribute("READSEMESS");
                session.removeAttribute("READREMESS");
                session.removeAttribute("REPLYMESS");
                session.removeAttribute("REPLYMESSSUB");
                Account getAcc = (Account) session.getAttribute("ACCOUNT");
                if (getAcc != null) {
                    int sentAccID = getAcc.getAccountID();
                    String sentEmail = getAcc.getEmailAddress();
                    String content = request.getParameter("txtRepContent");
                    String subject = request.getParameter("txtRepSubject");
                    String receivedEmail = request.getParameter("txtRepEmail");
                    AccountDAO checkAccDAO = new AccountDAO();
                    Account checkAcc = checkAccDAO.checkEmail(receivedEmail);
                    if (checkAcc != null) {
                        int receivedAccID = checkAcc.getAccountID();
                        MessageDAO sentAccDAO = new MessageDAO();
                        sentAccDAO.sendMessage(sentAccID, receivedEmail, subject, content);
                        MessageDAO receivedAccDAO = new MessageDAO();
                        String receivedStatus = "unread";
                        receivedAccDAO.receivedMessage(receivedAccID, sentEmail, subject, content, receivedStatus);
                        session.setAttribute("REPLYMESSAGESUCESS", "Message is sent to " + receivedEmail + "!!!");
                    } else {
                        session.setAttribute("REPLYMESSAGEERROR", "Message can't be sent to " + receivedEmail + "!!!");
                    }
                    response.sendRedirect(urlsent);
                } else if (getAcc == null) {
                    response.sendRedirect(Common.Global.loginpage);
                }
            } else if (action.equals("deleteReMess")) {
                int reMessID = Integer.parseInt(request.getParameter("deleteReMessageID"));
                MessageDAO messDAO = new MessageDAO();
                boolean check = messDAO.deleteReMess(reMessID);
                if (check) {
                    session.setAttribute("DELETEREMESS", "Message is deleted!!!");
                } else {
                    session.setAttribute("DELETEREERR", "Message can't be deleted!!!");
                }
                response.sendRedirect(urlreceived);
            } else if (action.equals("deleteSeMess")) {
                int seMessID = Integer.parseInt(request.getParameter("deleteSeMessageID"));
                MessageDAO messDAO = new MessageDAO();
                boolean check = messDAO.deleteSeMess(seMessID);
                if (check) {
                    session.setAttribute("DELETESEMESS", "Message is deleted!!!");
                } else {
                    session.setAttribute("DELETESEERR", "Message can't be deleted!!!");
                }
                response.sendRedirect(urlsent);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);




    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);




    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";


    }// </editor-fold>
}
